package com.qst.rongxiaotong.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qst.rongxiaotong.context.BaseContext;
import com.qst.rongxiaotong.exception.AccountNotFoundException;
import com.qst.rongxiaotong.exception.MessageConstant;
import com.qst.rongxiaotong.exception.PasswordErrorException;
import com.qst.rongxiaotong.mapper.UserMapper;
import com.qst.rongxiaotong.pojo.DTO.UserDTO;
import com.qst.rongxiaotong.pojo.User;
import com.qst.rongxiaotong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private  Integer pageSize = 10;


    @Override
    public User finduser() {

        return userMapper.getByUsername(BaseContext.getCurrentuserName());
    }

    @Override
    public void update(User user) {

        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void delete(String userName) {
        userMapper.deleteByPrimaryKey(userName);
    }

    @Override
    public User selectByUserName(String userName) {
        User user = userMapper.selectByPrimaryKey(userName);
        return user;
    }

    @Override
    public PageInfo<User> findPage(Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectAll();
        PageInfo<User> userPageInfo = new PageInfo<User>(users);
        return userPageInfo;
    }

    @Override
    public User login(UserDTO userDTO) {
        String username = userDTO.getUsername(); // 获取用户名
        String password = userDTO.getPassword(); // 获取密码

        // 1. 根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        // 2. 处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 密码比对（MD5加密）
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }


        // 3. 返回员工实体对象
        return user;
    }

}
